<template>
  <CustomNav title="修改姓名" />
  <view class="content">
    <u-input
      placeholder="请输入姓名"
      v-model="nickname"
      maxlength="4"
      @change="change"
    ></u-input>
  </view>

  <view class="default-button" @click="handleUpdate">确认保存</view>
</template>

<script setup>
import CustomNav from "@/components/CustomNav/index.vue";
import { Alert, unAlert, chineseReg } from "../../utils/tool";
import { updateUserData } from "@/api/user";
import { getItem, setItem, updateItem } from "../../utils/localStorage";

onMounted(() => {
  // nickname.value = getItem("userInfo").username;
});

const nickname = ref("");
const change = (e) => {
  nickname.value = e;
};

const handleUpdate = async () => {
  if (!nickname.value) {
    Alert("请输入姓名");
    return;
  } else if (!chineseReg(nickname.value)) {
    Alert("请输入中文");
    return;
  } else if (getItem("userInfo").username == nickname.value) {
    Alert("姓名与之前一致！");
    return;
  }

  Alert("加载中", "loading", 0, true);

  const res = await updateUserData({
    id: getItem("userInfo").id,
    username: nickname.value,
  });

  // console.log("修改姓名Api：", nickname.value);

  if (res.data.code == 200) {
    Alert("修改成功", "success");
    updateItem("userInfo", "username", nickname.value);
    setTimeout(() => {
      uni.navigateBack();
    }, 700);
  }
};
</script>
<script>
export default {
  name: "",
};
</script>

<style lang="scss" scoped>
.content {
  border-bottom: 1px solid #ccc;
  margin: 20px;
}
:deep(.u-input) {
  // border: 1px solid red;
}
</style>
